{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# tensorflow 2.0\n",
    "import tensorflow as tf\n",
    "size = 32\n",
    "embedding_dim = 16\n",
    "num_positive_samples = 3\n",
    "num_negative_samples = 6\n",
    "batch_size = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# generate data\n",
    "tf.random.set_seed(1234)\n",
    "# positive\n",
    "subset = tf.random.uniform((batch_size, num_positive_samples + 1), \n",
    "                  maxval=size, dtype=tf.int32)\n",
    "src, pos = tf.split(subset, [1, -1], axis=-1)\n",
    "assert src.shape == (batch_size,  1)\n",
    "assert pos.shape == (batch_size, num_positive_samples)\n",
    "# negative\n",
    "negs = tf.random.uniform((batch_size, num_negative_samples), \n",
    "                  maxval=size, dtype=tf.dtypes.int32)\n",
    "assert negs.shape == (batch_size, num_negative_samples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# embed_table\n",
    "embed_table = tf.random.uniform((size, embedding_dim))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# encode\n",
    "embedding = tf.nn.embedding_lookup(embed_table, src)\n",
    "assert embedding.shape == (batch_size,  1, embedding_dim)\n",
    "pos_embedding = tf.nn.embedding_lookup(embed_table, pos)\n",
    "assert pos_embedding.shape == (batch_size,  num_positive_samples, embedding_dim)\n",
    "negs_embedding = tf.nn.embedding_lookup(embed_table, negs)\n",
    "assert negs_embedding.shape == (batch_size,  num_negative_samples, embedding_dim)\n",
    "\n",
    "logits = tf.matmul(embedding, pos_embedding, transpose_b=True)\n",
    "assert logits.shape == (batch_size,  1, num_positive_samples)\n",
    "negs_logits = tf.matmul(embedding, negs_embedding, transpose_b=True)\n",
    "assert negs_logits.shape == (batch_size,  1, num_negative_samples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute mrr\n",
    "mrr_all = tf.concat((negs_logits, logits), axis=2)\n",
    "mrr_size = mrr_all.shape[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: id=46, shape=(), dtype=float32, numpy=0.4496528>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_, indices_of_ranks = tf.nn.top_k(mrr_all, k=mrr_size)\n",
    "_, ranks = tf.nn.top_k(-indices_of_ranks, k=mrr_size)\n",
    "mrr = tf.reduce_mean(tf.math.reciprocal(tf.cast(ranks[:, :, -1] + 1, tf.float32)))\n",
    "mrr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute loss, method one\n",
    "pos_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n",
    "    labels=tf.ones_like(logits), logits=logits)\n",
    "negs_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n",
    "          labels=tf.zeros_like(negs_logits), logits=negs_logits)\n",
    "loss1 = tf.reduce_sum(pos_xent) + tf.reduce_sum(negs_xent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute loss, method two\n",
    "pos_loss = tf.math.log_sigmoid(tf.reduce_sum(logits, axis=2))\n",
    "negs_loss = tf.math.log_sigmoid(tf.reduce_sum(-negs_logits, axis=2))\n",
    "loss2 = -tf.math.reduce_sum(pos_loss + negs_loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(<tf.Tensor: id=75, shape=(), dtype=float32, numpy=216.56586>,\n",
       " <tf.Tensor: id=90, shape=(), dtype=float32, numpy=215.28963>)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loss1, loss2"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
